package com.ljw.i18demo.exception;

import com.ljw.i18demo.common.MessageUtils;
import com.ljw.i18demo.common.ReturnResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author LiuJunWen
 * @Date 2020/5/19 23:01
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ReturnResponse handler(Exception e, HttpServletResponse response) {
        log.debug("[GlobalExceptionHandler] handler...", e);
        ReturnResponse m = null;
        if (e instanceof BindException) {
            //判断是 校验异常，就处理
            try {
                BindException me = (BindException) e;
                StringBuilder messageBuilder = new StringBuilder();
                for (ObjectError error : me.getBindingResult().getAllErrors()) {
                    //获取校验的信息
                    messageBuilder.append(error.getDefaultMessage()).append(",");
                }
                // 封装成自己固定的格式
                m = new ReturnResponse(HttpStatus.BAD_REQUEST.value(), messageBuilder.substring(0,
                        messageBuilder.length() -1));
                response.setStatus(HttpStatus.BAD_REQUEST.value());
            } catch (Exception e1) {
                m = new ReturnResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "未知异常");
                response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            }
        } else {
            m = new ReturnResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), "未知异常");
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        }

        return m;
    }
}
